<template>
	<view class="page">
		<view class="topBox" @tap="logout" :style="{paddingTop:jiaonangHight+'px',height:selectHeight+'px'}">
			<image src="../../static/index/icon.png" />
			<view class="topBox_title"> 设备二维码 </view>
		</view>
		<view class="card">
			<view class="dis">
				<image :src="imgCode" mode="" class="img_code" @tap.stop="lockImage(case_code)">
				</image>
				<view>
					<view class="" style="display: flex;align-items: center;justify-content: space-between;padding: 0 30rpx;">
						<view class="btn" @click="goToConnectPage()">
							连接打印机
						</view>
						<view class="btn" @click="printLabel()">
							打印
						</view>
					</view>
				
					<!-- 钉钉使用的 canvas -->
					<canvas v-if="platform === 'DingTalk'" id="dingtalkCanvas" canvas-id="dingtalkCanvas"
						ref="dingtalkCanvas" :width="canvasWidthResponsive" :height="canvasHeightResponsive"></canvas>

					<!-- 微信和飞书使用的 canvas -->
					<canvas v-else-if="platform === 'WeChat' || platform === 'FeiShu'" ref="wechatFeishuCanvas"
						canvas-id="wechatFeishuCanvas" :style="{
				              width: canvasWidthResponsive + 'px',
				              height: canvasHeightResponsive + 'px'
				            }"></canvas>
				</view>

			</view>
		</view>
	</view>
</template>

<script>
	import {
		usePrint
	} from '@/utils/print';
	import {
		nextTick
	} from "@vue/composition-api";
	import * as tsc from "@/components/gprint/tsc.js";
	const {
		startJob,
		startDrawLabel,
		drawText,
		drawBarcode,
		drawQRCode,
		drawRectangle,
		drawLine,
		drawImage,
		endDrawLabel,
		print,
		didReadPrintCountInfo,
		didReadPrintErrorInfo,
		getMultiple,
		getSn,
		setPlatform
	} = usePrint();

	export default {
		data() {
			return {
				id: null,
				detail: {},
				imageSrc: "",
				canvasWidth: 200,
				canvasHeight: 200,
				quantity: 1,
				printed: 0,
				platform: null,
				res: '',
				imgCode:'',
				selectHeight: '', //顶部盒子高度，
				jiaonangHight: '', //胶囊顶部高度
			}
		},
		computed: {
			// 响应式宽高
			canvasWidthResponsive() {
				return this.canvasWidth;
			},
			canvasHeightResponsive() {
				return this.canvasHeight;
			},

		},
		created() {
			this.setPlatform()
		},
		onLoad(e) {
			this.getMenuHight()
			this.imgCode = e.imgCode
		},
		methods: {
			logout(){
				uni.showModal({
					title: "提示",
					content: "是否需要打印该二维码？",
					showCancel: true,
					success: async ({
						confirm,
						cancel
					}) => {
						if (confirm) {
							await this.saveimgtoAlbum(this.imgCode);
						} else {
							console.log('取消---------')
							setTimeout(() => {
								uni.navigateTo({
									url:'/pages/home/index'
								})
							}, 200)
						}
					},
					fail: (err) => {
						resolve();
					},
				});
			},
			
			getMenuHight() {
				let res = wx.getMenuButtonBoundingClientRect()
				this.selectHeight = res.height+4;
				this.jiaonangHight = res.top;
			},
			// 保存到相册
			savePhoto(imgurl) {
				console.log(imgurl,'---------')
				return new Promise((resolve, reject) => {
					uni.authorize({
						scope: "scope.writePhotosAlbum",
						success: () => {
							uni.getImageInfo({
								src: imgurl,
								success: (image) => {
									uni.saveImageToPhotosAlbum({
										filePath: image.path,
										success: () => {
											uni.showModal({
												content: "图片已保存，请在相册查看！",
												showCancel: false,
												confirmText: "确定",
												confirmColor: "#333",
												success: () => {
													setTimeout(() => {
														uni.navigateTo({
															url:'/pages/home/index'
														})
													}, 500)
												},
											});
										},
										fail: (err) => {
											resolve();
										},
									});
								},
							});
						},
						fail: (err) => {
							uni.showToast({
								title: err.errMsg,
								icon: "none",
								success: () => {
									setTimeout(() => {
										resolve();
									}, 1500);
								},
							});
						},
					});
				});
			},
			// 检测是否有保存到相册权限
			saveimgtoAlbum(imgurl) {
				return new Promise((resolve, reject) => {
					uni.getSetting({
						success: async (res) => {
							if (!res.authSetting["scope.writePhotosAlbum"]) {
								uni.showModal({
									title: "授权提示",
									content: "需要写入相册权限，请确认授权，否则图片无法保存到本地",
									showCancel: true,
									success: async ({
										confirm,
										cancel
									}) => {
										if (confirm) {
											await this.savePhoto(imgurl);
											resolve();
										} else {
											uni.showToast({
												title: "已取消授权",
												icon: "none",
												success: () => {
													setTimeout(() => {
														resolve();
													}, 1500);
												},
											});
										}
									},
									fail: (err) => {
										resolve();
									},
								});
							} else {
								await this.savePhoto(imgurl);
								resolve();
							}
						},
					});
				});
			},
			
			setPlatform() {
				uni.getSystemInfo({
					success: (res) => {
						console.log("res.hostName", res.hostName)
						switch (res.hostName) {
							case 'WeChat':
							case 'wxwork':
								setPlatform('微信');
								this.platform = 'WeChat';
								break;
							case 'DingTalk':
								setPlatform('钉钉');
								this.platform = 'DingTalk';
								break;
							case 'Feishu':
								setPlatform('飞书');
								this.platform = 'FeiShu';
								break;
							default:
								console.log('未识别的平台');
						}
						console.log('platform', this.platform)
					},
				});
			},
			goToConnectPage() {
				uni.navigateTo({
					url: '../index/printer'
				});
			},

			printLabel() {
				this.getNetworkImage(this.imgCode)
				var fileName = new Date().getTime() + ".png";

				let connectStatus = 0;
				getSn((res) => {
					console.log('--------sn', res)
					if (res.code === -4) {
						connectStatus = -4;
					}

					if (connectStatus === -4) {
						uni.showToast({
							title: '打印机未连接',
							icon: 'none'
						});
						return;
					}

					this.printed = 0
					// uni.showToast({
					// 	title: '开始打印'
					// });

					didReadPrintCountInfo((res) => {
						// console.log('打印成功回调',res.count);
					});

					didReadPrintErrorInfo((res) => {
						console.log(res.errCode);
					});

					startJob(1, 3, this.quantity, () => {
						uni.showToast({
							title: '开始打印'
						});
						this.starPrint();
					});
				});


			},
			getNetworkImage(url) {
				return new Promise((resolve, reject) => {
					uni.downloadFile({
						url,
						success: (e) => {
							const p = e.tempFilePath
							if (p.indexOf('json') > -1) {
								reject(p)
								return false
							}
							this.res = p
							resolve(p)
							console.log(p, 'ppppppppppp')
						},
						fail: (r) => {
							reject(r)
						}
					})
				})
			},

			async starPrint() {
				this.printed += 1
				//标签尺寸
				const labelWidth = 70
				const labelHeight = 50

				//B3S/B1/B21/B203/K3/K3W的multiple传8，B32/Z401/M2的multiple传11.81
				const multiple = 11.81
				this.canvasWidth = labelWidth * multiple
				this.canvasHeight = labelHeight * multiple
				await nextTick()
				console.log('开始绘制', this.platform);
				let canvasId = '';

				if (this.platform === 'DingTalk') {
					canvasId = 'dingtalkCanvas';
				} else if (this.platform === 'WeChat' || this.platform === 'FeiShu') {
					canvasId = 'wechatFeishuCanvas';
				}
				const ctx = uni.createCanvasContext(canvasId);
				console.log('ctx', ctx)
				ctx.setFillStyle('white');
				ctx.fillRect(0, 0, 1000, 800);

				ctx.draw(false, () => {
					console.log('绘制完成drawQRCode33');
					startDrawLabel(canvasId, this.$refs, labelWidth, labelHeight, 270)
					drawImage(this.res,0, 0, 71, 50, 0);
					endDrawLabel(() => {
						print(1, () => {
							if (this.quantity > this.printed) {
								this.starPrint();
							}
						})
					});
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	canvas {
		/* 将canvas的左边缘定位到屏幕宽度的100%处，使其完全超出屏幕左侧显示区域 */
		position: absolute;
		left: 100%;
		width: 100%;
		height: 100%;
	}

	.dis {
		text-align: center;

		.img_code {
			margin-top: 20rpx;
			width: 604rpx;
			height: 424rpx;
			box-sizing: border-box;
		}
	}

	.btn {
		width: 164rpx;
		font-size: 28rpx;
		font-family: PingFang SC-Regular, PingFang SC;
		font-weight: 400;
		color: #1A66FF;
		padding: 6rpx 32rpx;
		border-radius: 32rpx;
		opacity: 1;
		border: 2px solid #1A66FF;
		margin: 20rpx auto;
	}

	.border {
		border-bottom: 2rpx solid #f7f8fb;
	}

	.page {
		background-color: #f7f8fb;
		min-height: 100vh;
	}

	.ful {
		display: flex;
		justify-content: space-between;
	}

	.ful_left {
		color: #303030;
		padding: 20rpx;
	}

	.ful_right {
		padding: 20rpx;
	}
	.topBox {
		color: #fff;
		background-color: #1a66ff;
		display: flex;
		align-items: center;
		justify-content: flex-start;
		.topBox_title {
			margin-left: 250rpx;
			font-size: 30rpx;
		}

		image {
			width: 20rpx;
			height: 30rpx;
			margin-left: 30rpx;
		}
	}
	.card {
		font-size: smaller;
		color: #999999;

		margin: 30rpx;
		background-color: #fff;
		padding: 10rpx;
		border-radius: 10rpx;
		box-shadow: 10rpx 10rpx 10rpx 10rpx;
	}
</style>